package com.lee.rpc.protocal.code;

import com.lee.rpc.protocal.core.Header;
import com.lee.rpc.protocal.core.RpcProtocal;
import com.lee.rpc.protocal.serial.ISerializer;
import com.lee.rpc.protocal.serial.SerializerManager;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

public class RpcEncode extends MessageToByteEncoder<RpcProtocal<Object>>{

	@Override
	protected void encode(ChannelHandlerContext ctx, RpcProtocal<Object> msg, ByteBuf out) throws Exception {
		// TODO Auto-generated method stub
		Header header = msg.getHeader();
		out.writeShort(header.getMagic());
		out.writeByte(header.getSerialType());
		out.writeByte(header.getReqType());
		out.writeLong(header.getRequestId());
		
		ISerializer serializer = SerializerManager.getSerializer(header.getSerialType());
		byte[] body = serializer.serialize(msg.getContent());
		out.writeInt(body.length); 
		out.writeBytes(body);
		
		
	}

}
